<template>
    <div class="admin-page">
        <div class="page-header">
            <div style="display: flex;justify-content: space-between">
                <div style="display: flex; flex-wrap: wrap; align-items: center; gap: 15px; margin-bottom: 15px;">
                    <div style="display: flex; align-items: center;" class="search-item">
                        <span class="search-label">日期:</span>
                        <el-date-picker
                            v-model="searchForm.date"
                            type="month"
                            size="small"
                            style="width: 130px;"
                            placeholder="选择日期"
                            value-format="yyyy-M"
                        />
                    </div>
                    <div style="display: flex; align-items: center;" class="search-item">
                        <span class="search-label">状态:</span>
                        <el-select v-model="searchForm.state" size="small" style="width: 110px;" placeholder="全部" clearable>
                            <el-option
                                v-for="item in statusOptions"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value">
                            </el-option>
                        </el-select>
                    </div>
                    <div style="display: flex; align-items: center;" class="search-item">
                        <span class="search-label">渠道用户:</span>
                        <el-select v-model="searchForm.channel_id" size="small" style="width: 110px;" placeholder="全部" clearable>
                            <el-option v-for="(item, index) in qudaoList" :key="index" :label="item.name" :value="item.id"></el-option>
                        </el-select>
                    </div>
                </div>
                <div style="display: flex; align-items: center; gap: 15px; margin-bottom: 15px;">
                    <el-button type="primary" size="small" @click="handleSearch">搜索</el-button>
                    <el-button type="success" size="small" style="margin-left: 10px;" @click="handleReset">重置</el-button>
                    <el-button size="small" @click="exportToExcel">导出</el-button>
                </div>
            </div>

            <el-table :data="tableData" height="560" border style="width: 100%;overflow-y: auto"
                      :header-cell-style="{background:'#FAFAFA',color:'#666', fontSize:'13px'}" size="small">
                <el-table-column prop="huifu_id" label="汇付ID" width="250" align="center" />
                <el-table-column prop="alipay_name" label="用户名" width="100" align="center" />
                <el-table-column prop="idcard" label="证件号码" width="250" align="center" />
                <el-table-column prop="name" label="用户余额" width="100" align="center" />
                <el-table-column prop="bank_card" label="银行卡号" align="center" />
                <el-table-column label="支付开关" width="100" align="center">
                    <template slot-scope="scope">
                        <el-switch
                            v-model="scope.row.month"
                            :active-value="1"
                            :inactive-value="0"
                            @change="handleSwitchChange(scope.row, 'month')">
                        </el-switch>
                    </template>
                </el-table-column>
                <el-table-column label="提现开关" width="150" align="center">
                    <template slot-scope="scope">
                        <el-switch
                            v-model="scope.row.total_price"
                            :active-value="1"
                            :inactive-value="0"
                            @change="handleSwitchChange(scope.row, 'total_price')">
                        </el-switch>
                    </template>
                </el-table-column>
                <el-table-column prop="is_up_name" label="创建时间" width="100" align="center" />
                <el-table-column prop="ave_dis" label="更新时间" width="100" align="center" />
                <el-table-column align="center" label="操作" width="130">
                    <template slot-scope="scope">
                        <el-button type="text" size="small" @click="handleEdit(scope.row)" icon="el-icon-edit">编辑
                        </el-button>
                        <el-button type="text" size="small" @click="handleDetail(scope.row)" icon="el-icon-view">详情
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>

            <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="currentPage"
                :page-size="pageSize"
                layout="total, prev, pager, next"
                :total="total"
            />
        </div>

        <!-- 编辑弹窗 -->
        <el-dialog title="编辑用户信息" :visible.sync="editDialogVisible" width="600px" class="edit-dialog">
            <el-form :model="editForm" :rules="editRules" ref="editForm" label-width="120px">
                <el-form-item label="汇付ID" prop="id">
                    <el-input v-model="editForm.id" disabled></el-input>
                </el-form-item>
                <el-form-item label="用户名" prop="uid">
                    <el-input v-model="editForm.uid" disabled></el-input>
                </el-form-item>
                <el-form-item label="证件号码" prop="username">
                    <el-input v-model="editForm.username"></el-input>
                </el-form-item>
                <el-form-item label="用户余额" prop="name">
                    <el-input v-model="editForm.name" type="number"></el-input>
                </el-form-item>
                <el-form-item label="银行卡号" prop="year">
                    <el-input v-model="editForm.year"></el-input>
                </el-form-item>
                <el-form-item label="支付开关" prop="month">
                    <el-switch v-model="editForm.month" active-text="开启" inactive-text="关闭"></el-switch>
                </el-form-item>
                <el-form-item label="提现开关" prop="total_price">
                    <el-switch v-model="editForm.total_price" active-text="开启" inactive-text="关闭"></el-switch>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="editDialogVisible = false" size="small">取消</el-button>
                <el-button type="primary" @click="submitEdit" size="small">确定</el-button>
            </div>
        </el-dialog>


    </div>
</template>

<script>
export default {
    data() {
        return {
            searchForm: {
                date: '',
                state: '',
                channel_id:""
            },
            withdrawDialogVisible: false,
            tableData: [],
            statusOptions: [
                { label: '全部', value: '' },
                { label: '已发放', value: 1 },
                { label: '待发放', value: 0 },
                { label: '不发放', value: 2 }
            ],
            currentPage: 1,
            pageSize: 15,
            total: 0,
            qudaoList:[],
            isEditing: {},
            editDialogVisible: false,
            editForm: {},
            editRules: {
                id: [{ required: true, message: '请选择用户', trigger: 'change' }],
                uid: [{ required: true, message: '请选择用户', trigger: 'change' }],
                username: [{ required: true, message: '请输入证件号码', trigger: 'blur' }],
                name: [{ required: true, message: '请输入用户余额', trigger: 'blur' }],
                year: [{ required: true, message: '请输入银行卡号', trigger: 'blur' }],
                month: [{ required: true, message: '请选择支付开关', trigger: 'change' }],
                total_price: [{ required: true, message: '请选择提现开关', trigger: 'change' }]
            },

        }
    },
    created() {
        this.getTableData()
        this.fetchAdminList1()
    },
    methods: {
        handleEdit(row) {
            this.editForm = { ...row };
            this.editDialogVisible = true;
            // 重置表单
            this.$nextTick(() => {
                this.$refs.editForm && this.$refs.editForm.resetFields();
            });
        },
        handleDetail(row) {
            // 将数据存储到localStorage，然后跳转到详情页面
            localStorage.setItem('huifuUserDetail', JSON.stringify(row));
            this.$router.push('/huifu/user/detail');
        },
        exportToExcel() {
            // 从本地存储中获取 userInfo
            const userInfo = JSON.parse(localStorage.getItem('userInfo'));
            if (!userInfo || !userInfo.token) {
                // 如果 token 不存在，给出提示
                this.$message.error('token 不存在，请重新登录');
                return;
            }
            const token = userInfo.token;
            // 拼接搜索条件参数
            let queryParams = `token=${token}`;
            const {state , search , date} = this.searchForm;
            if (state !== undefined && state !== null && state !== '') {
                queryParams += `&state=${state}`;
            }

            if (search !== undefined && search !== null && search !== '') {
                queryParams += `&search=${search}`;
            }

            if (date !== undefined && date !== null && date !== '') {
                queryParams += `&date=${date}`;
            }
            // 构造完整的 URL
            // const url = `http://localhost:8081/admin/UserWeightDiv/userWeightDivExport?${queryParams}`;
            const url = this.$appConfig.baseUrl + `admin/UserWeightDiv/userWeightDivExport?${queryParams}`;
            // 在新窗口中打开页面
            window.open(url, '_blank');
        },
        getStatusType(status) {
            switch (status) {
                case '0': return 'info';
                case '1': return 'success';
                case '2': return 'warning';
                default: return 'info';
            }
        },

        // 根据状态值获取标签效果
        getStatusEffect(status) {
            return status === '2' ? 'dark' : 'light';
        },

        // 根据状态值获取显示文本
        getStatusText(status) {
            const statusMap = {
                '0': '待发放',
                '1': '已发放',
                '2': '不发放'
            };
            return statusMap[status] || '未知';
        },

        // 调用后端接口更新状态
        changeLevel(id, status) {
            this.$http.post('/admin/UserWeightDiv/setUserWeightDivState', {id:id,state:status}).then(result => {
                if(result.code === 200){

                    this.getTableData()
                }
            });
            // 这里调用你的 changeLevel 方法
        },
        fetchAdminList1() {
            const params = {
                type: 3,
                page: this.currentPage,
                limit: this.pageSize
            };
            this.$http.get('/admin/single/lists', {params}).then(result => {
                console.log(result)
                const newArr = []
                if(result.code === 200){
                    result.data.data.forEach(item=>{
                        newArr.push({name:item.name,id:item.id})
                    })
                    console.log(newArr)
                    this.qudaoList = newArr
                }
            });
        },
        getTableData(params = {}) {
            const defaultParams = {
                page: this.currentPage,
                ...params
            };
            this.$message.info({
                message: '正在加载数据...',
                duration: 0,
                showClose: true,
                iconClass: 'el-icon-loading'
            });
            this.$http.get('/admin/HuiFuApi/getHuiFuUserList',{params: defaultParams}).then(result => {
                if (result.code === 200) {
                    this.tableData = result.data.data;
                    this.total = result.data.total || this.tableData.length;
                } else {
                    this.$message.error(result.msg);
                }
            }).catch(error => {
                console.error('获取列表失败:', error);
                this.$message.error('获取数据失败，请重试');
            }).finally(() => {
                this.$message.closeAll();
            });
        },
        toggleStatus(row) {
            row.status = row.status ? 0 : 1
        },
        handleSearch() {
            this.searchParams = {
                ...this.searchForm,
            };
            this.currentPage = 1;
            this.getTableData(this.searchParams)
        },
        handleReset() {
            this.searchForm = {
                date: '',
                state: '',
                channel_id:""
            }
            this.getTableData()
        },
        handleSizeChange(val) {
            this.pageSize = val
            this.getTableData()
        },
        handleCurrentChange(val) {
            this.currentPage = val
            this.getTableData()
        },
        submitEdit() {
            this.$refs.editForm.validate(valid => {
                if (valid) {
                    this.$http.post('/admin/UserWeightDiv/updateUserWeightDiv', this.editForm).then(result => {
                        if (result.code === 200) {
                            this.$message.success('编辑成功');
                            this.editDialogVisible = false;
                            this.getTableData();
                        } else {
                            this.$message.error(result.msg);
                        }
                    }).catch(error => {
                        console.error('编辑失败:', error);
                        this.$message.error('编辑失败，请重试');
                    });
                }
            });
        },
        handleSwitchChange(row, field) {
            const params = {
                id: row.id,
                [field]: row[field]
            };
            this.$http.post('/admin/UserWeightDiv/updateUserWeightDiv', params).then(result => {
                if (result.code === 200) {
                    this.$message.success('状态更新成功');
                } else {
                    this.$message.error(result.msg);
                    // 如果更新失败，恢复原值
                    row[field] = row[field] === 1 ? 0 : 1;
                }
            }).catch(error => {
                console.error('状态更新失败:', error);
                this.$message.error('状态更新失败，请重试');
                // 如果更新失败，恢复原值
                row[field] = row[field] === 1 ? 0 : 1;
            });
        }
    }
}
</script>

<style scoped lang="less">
.admin-page {
    padding: 20px;

    .search-label {
        margin-right: 10px;
        color: #606266;
    }

    .el-table {
        margin-top: 20px;
    }

    .el-pagination {
        margin-top: 20px;
        text-align: right;
    }

    .clickable-amount {
        color: #409EFF;
        cursor: pointer;
        font-weight: bold;

        &:hover {
            text-decoration: underline;
        }
    }
}

.amount-edit-dialog {
    border-radius: 8px;
    overflow: hidden;

    /deep/ .el-dialog__header {
        background-color: #f5f7fa;
        padding: 15px 20px;

        .el-dialog__title {
            font-weight: bold;
            color: #303133;
        }
    }

    /deep/ .el-dialog__body {
        padding: 25px 20px 10px;
    }

    .edit-form {
        margin-top: 10px;

        /deep/ .el-form-item__label {
            font-weight: 500;
            color: #606266;
        }

        .info-item {
            /deep/ .el-input__inner {
                background-color: #f5f7fa;
                color: #606266;
            }
        }
    }

    /deep/ .el-dialog__footer {
        border-top: 1px solid #ebeef5;
        padding: 15px 20px;
    }

    .dialog-footer {
        text-align: right;
    }
}

.confirm-dialog {
    border-radius: 8px;

    /deep/ .el-dialog__header {
        padding: 15px 20px;
    }

    /deep/ .el-dialog__body {
        padding: 10px 40px;
    }

    .confirm-content {
        display: flex;
        align-items: flex-start;
        margin-bottom: 15px;

        .warning-icon {
            font-size: 24px;
            color: #E6A23C;
            margin-right: 15px;
            margin-top: 3px;
        }

        .confirm-text {
            flex: 1;

            .confirm-title {
                font-size: 16px;
                font-weight: bold;
                color: #303133;
                margin-bottom: 5px;
            }

            .confirm-desc {
                color: #606266;
                line-height: 1.5;
            }
        }
    }

    .confirm-details {
        background-color: #f8f8f8;
        border-radius: 4px;
        padding: 15px;
        margin-bottom: 10px;

        .detail-item {
            display: flex;
            margin-bottom: 8px;

            &:last-child {
                margin-bottom: 0;
            }

            .detail-label {
                width: 70px;
                color: #909399;
            }

            .detail-value {
                flex: 1;
                color: #303133;
                font-weight: 500;
            }
        }
    }
}

/deep/ .el-dialog__header{
    padding: 10px !important;
}

.edit-dialog {
    border-radius: 8px;
    overflow: hidden;

    /deep/ .el-dialog__header {
        background-color: #f5f7fa;
        padding: 15px 20px;

        .el-dialog__title {
            font-weight: bold;
            color: #303133;
        }
    }

    /deep/ .el-dialog__body {
        padding: 25px 20px 10px;
    }

    /deep/ .el-dialog__footer {
        border-top: 1px solid #ebeef5;
        padding: 15px 20px;
    }

    .dialog-footer {
        text-align: right;
    }
}

.edit-dialog {
    .el-form {
        .el-form-item {
            margin-bottom: 20px;

            /deep/ .el-form-item__label {
                font-weight: 500;
                color: #606266;
            }

            /deep/ .el-input__inner {
                border-radius: 4px;
            }

            /deep/ .el-switch {
                margin-top: 5px;
            }
        }
    }
}


</style>
